# Maintainer: Christoph Reiter <reiter.christoph@gmail.com>

_realname=whisper.cpp
pkgbase=mingw-w64-${_realname}
pkgname=("${MINGW_PACKAGE_PREFIX}-${_realname}")
pkgver=1.4.2
pkgrel=1
pkgdesc="Port of OpenAI's Whisper model in C/C++ (mingw-w64)"
arch=('any')
mingw_arch=('ucrt64' 'clang64' 'clangarm64')
url='https://github.com/ggerganov/whisper.cpp'
license=('spdx:MIT')
depends=(
  "${MINGW_PACKAGE_PREFIX}-openblas"
  "${MINGW_PACKAGE_PREFIX}-SDL2"
  "${MINGW_PACKAGE_PREFIX}-gcc-libs"
)
makedepends=(
  "${MINGW_PACKAGE_PREFIX}-cc"
  "${MINGW_PACKAGE_PREFIX}-cmake"
  "${MINGW_PACKAGE_PREFIX}-ninja"
  "${MINGW_PACKAGE_PREFIX}-pkgconf"
)
source=("https://github.com/ggerganov/whisper.cpp/archive/refs/tags/v${pkgver}.tar.gz"
        "0001-fix-importlib-location.patch")
sha256sums=('1b988dcc77fca55f188dbc4e472f971a80854c1d44309cf3eaab9d5677f175e1'
            'e2c780b44809e940a4919dae65f49a8e2792af632ec3bf12bc0cdbdea4ba2e00')

prepare() {
  cd "${srcdir}"/${_realname}-${pkgver}

  patch -p1 -i "${srcdir}/0001-fix-importlib-location.patch"
}

build() {
  mkdir -p "${srcdir}/build-${MSYSTEM}" && cd "${srcdir}/build-${MSYSTEM}"

  declare -a extra_config
  if check_option "debug" "n"; then
    extra_config+=("-DCMAKE_BUILD_TYPE=Release")
  else
    extra_config+=("-DCMAKE_BUILD_TYPE=Debug")
  fi

  CFLAGS+=" $(pkgconf.exe --cflags openblas)" \
  LDFLAGS+=" -Wl,--export-all-symbols" \
  MSYS2_ARG_CONV_EXCL="-DCMAKE_INSTALL_PREFIX=" \
    "${MINGW_PREFIX}"/bin/cmake.exe \
      -GNinja \
      -DCMAKE_INSTALL_PREFIX="${MINGW_PREFIX}" \
      -DWHISPER_SDL2=ON \
      -DWHISPER_OPENBLAS=ON \
      -DWHISPER_BUILD_EXAMPLES=ON \
      -DBUILD_SHARED_LIBS=ON \
      -DWHISPER_ALL_WARNINGS=OFF \
      "${extra_config[@]}" \
      ../${_realname}-${pkgver}

  "${MINGW_PREFIX}"/bin/cmake.exe --build .
}

package() {
  cd "${srcdir}/build-${MSYSTEM}"

  DESTDIR="${pkgdir}" "${MINGW_PREFIX}"/bin/cmake.exe --install .

  # Install the examples by prefixing them with whisper.cpp
  # except main.exe, which gets installed as plain whisper.cpp.exe
  for i in bin/*.exe; do
    install -Dm755 "${i}" \
      "${pkgdir}${MINGW_PREFIX}/bin/${_realname}-${i//bin\//}"
  done
  mv "${pkgdir}${MINGW_PREFIX}/bin/${_realname}-main.exe" \
    "${pkgdir}${MINGW_PREFIX}/bin/${_realname}.exe"

  install -Dm644 "${srcdir}/${_realname}-${pkgver}/LICENSE" "${pkgdir}${MINGW_PREFIX}/share/licenses/${_realname}/LICENSE"
}
